<template>
	<view class="safe-area-inset-bottom">
		<!-- 顶部自定义导航 -->
		<uni-nav-bar :fixed="true" backgroundColor="#00a660" color="#fff" height="90rpx">
			<block slot="left">
				<i class="iconfont nav_backIcon" @click="back">&#xe8b8;</i>
				<span style="font-size: 32rpx;">合同模板</span>
			</block>
			<block slot="right">
				<button size="mini" class="add_btn" @click="extractionTemplate"><i class="iconfont" style="margin-right: 2rpx;">&#xe682;</i>提取模板</span></button>
				<button size="mini" class="add_btn" @click="handleAdd"><i class="iconfont">&#xeaf3;</i>新增模板</span></button>
			</block>
		</uni-nav-bar>	
		<view class="swip_header" style="top:50px;">
			<view class="slot-box">
				<view style="width: 100%;">
					<uni-search-bar v-model="queryParams.name" type="text" @confirm="handleQuery" @input="handleQuery" placeholder="请输入模板名称" />
				</view>
			</view>
		</view>
		
		<!-- 列表 -->
		<view v-if="templateList != ''" class="listSearchTop cardList">
		  <uni-card :is-shadow="false" v-for="(item,index) in templateList" :key="index">
				<view class="flex_between">
					<p class="grid-hidden contract_Name" style="width: 85%;">{{ item.name }}</p>
					<switch color="#00a660" style="transform:scale(0.7)" :checked="item.status == 1 ?true:false"
						@change="switchChange(item)" v-if="item.isSystem == 1" disabled />
					<span v-else @click="switchChange(item)">
						<switch color="#00a660" style="transform:scale(0.7)" :checked="item.status == 1 ?true:false" disabled />
					</span>
				</view>
			<p class="grid-integral">模板编号：{{ item.templateNum }}</p>
			<p class="grid-integral">合同类型：{{ item.contractTypeName }}</p>
			<p class="grid-integral">签约主体：{{ item.signMax }}个</p>
			<p class="grid-integral">签署要求：
			<template v-for="(dictItem, index) in dicts.ec_contract_template_sign_set">
			  <template v-if="item.signSet == dictItem.value">
			    <!-- <uni-tag :text="dictItem.text" :type="dictItem.type"/> -->
				<span class="themeColor">{{dictItem.text}}</span>
			  </template>
			</template>
			</p>
			<p class="grid-integral">创建时间：{{item.createTime}}</p>
			<p class="grid-integral" v-if="item.updateTime != null">更新时间：{{item.updateTime}}</p>
			<p class="grid-integral" v-else>更新时间：--</p>	
			<!-- 更多操作 -->
			<view slot="actions" class="card-actions">
			  <view class="card-actions-item" @click.stop="setting(item)">
			    <text class="card-actions-item-text themeColor">设置</text>
			  </view>
			  <view class="card-actions-item" @click.stop="handleEdit">
			    <text class="card-actions-item-text warningColor">编辑</text>
			  </view>
			  <view class="card-actions-item" @click.stop="handleShare(item)">
			    <text class="card-actions-item-text themeColor">分享</text>
			  </view>
			  <view class="card-actions-item" @click.stop="handleDelete(item,index)">
			    <text class="card-actions-item-text errorColor">删除</text>
			  </view>
			</view>
		</uni-card>
		<!-- 加载更多 -->
		<uni-load-more color="#00a660" :status="loadStatus" />
		</view>
		<!-- 暂无数据 -->
		<luanqingEmpty :show="true" text="没有更多数据啦" v-else />
		<!-- 提取模板 -->
		<uni-popup ref="shareInput" type="dialog">
		   <uni-popup-dialog ref="inputClose"  mode="input" title="标准合同模板提取密码" v-model="shareCode" value="shareCode"
		   		placeholder="请输入标准合同模板提取密码" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		</view>
</template>

<script>
	import {
	  listTemplate,
	  getTemplate,
	  delTemplate,
	  addTemplate,
	  updateTemplate,
	  updateTemplateStatus
	} from "@/api/ec/console/busiConfig/template";
	import {listBycontractTypeId} from "@/api/ec/console/busiConfig/contractBusinessType";
	import {getContractTemplateByShareCode} from "@/api/ec/console/busiConfig/templateShare";
	import {listByCompanyId} from "@/api/ec/console/busiConfig/contractType";
	import luanqingEmpty from '@/components/luanqing-empty/luanqing-empty';
	import {listDept, treeselect} from "@/api/ec/console/org/dept";
	import {listStaffByDeptId} from "@/api/ec/console/org/staff";
	import {parseTime} from "@/utils/common";
	import {getDictsByNameForUni} from "@/utils/dicts";
	export default {
		components:{luanqingEmpty},
		data() {
			return {
				// 数据字典
				dicts: {
					ec_contract_template_sign_set:[]
				},
				total:0 ,//总条数
				loadStatus:'loading', //是否加载中 //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
				shareCode:'',//提取码 
				msgType:'info',
				templateList: [], // 合同类型列表
				title: "", // 弹出层标题
			    // 查询参数
			    queryParams: {
			        pageNum: 1,
			        pageSize: 10,
			        companyId: null,
			        name: null,
			        wordPath: null,
			        pageCount: null,
			        content: null,
			        ctype: null,
			        paramNum: null,
			        contractTypeId: null,
			        contractBusinessTypeId: null,
			        departmentIds: null,
			        operId: null,
			        updateTime: null,
			        createTime: null
			    },   
				form: {},
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请输入类型名称'
							},{
								minLength: 2, maxLength: 12,
								errorMessage: '长度在2-12个，不能有特殊字符',
								trigger: "change"
							}]
						},
						sort: {
							rules: [{
								required: true,
								errorMessage: '请输入排序'
							}]
						},					
				},
			}
		},
		created() {
			this.getList();
			this.getDicts();
			this.bindingRefreshData()
		},
		//上拉触底函数
		onReachBottom() {
		  if (this.loadStatus != 'noMore' && this.total > this.templateList.length) {
		    this.loadStatus = 'loading';
		    // 延迟500毫秒显示loading效果
		    setTimeout(() => {
		      // 执行查询的方法
		      this.getList(false);
		    }, 500)
		  } else {
		    // 停止加载
		    this.loadStatus = 'noMore'
		  }
		},
		beforeDestroy() {
		  this.unbindingRefreshData();
		},
		methods: {
			/** 绑定 */
			bindingRefreshData() {
			  // 刷新页面数据
			  uni.$on('refreshData', () => {
			    this.handleQuery();
			  });
			},
			/** 解除绑定 */
			unbindingRefreshData() {
			  uni.$off('refreshData');
			},
			back(){
				uni.switchTab({
					url:'/pages/common/contractManage/index'
				})
			},
			/**加载数据字典*/
			getDicts() {
			  this.dicts.ec_contract_template_sign_set = getDictsByNameForUni("ec_contract_template_sign_set");
			},
			/** 搜索 */
			handleQuery(){
				this.getList(true);      
			},
			/** 获取列表 */
			getList(reload) {
			  if (reload) {
			    this.queryParams.pageNum = 1;
			    this.loadStatus = 'more'
                this.$modal.loading();
			  }
			  listTemplate(this.queryParams).then(response => {
			    if (reload) {
			      uni.hideLoading()
			    }
			    this.total = response.total;
			    if (response.total > 0) {
			      const dataRows = response.rows;
			      this.templateList = reload ? dataRows : this.templateList.concat(dataRows);
			    } else {
			      this.templateList = [];
			    }
			    // 判断数据是否加载完全
			    if (response.total <= this.templateList.length) {
			      this.loadStatus = 'noMore'
			    }
			    // 页数+1
			    this.queryParams.pageNum++
			  }).catch(() => {
			    if (reload) {
			      uni.hideLoading()
			    }
			  });
			},
			// 输入提取码 获取模板
			extractionTemplate(){
				this.$refs.shareInput.open('center')
			},
			/** 确认提取 */
			dialogInputConfirm(value){
				uni.showLoading({
					title:"提取中"
				})
				getContractTemplateByShareCode({shareCode:value}).then((response)=>{
					uni.hideLoading()
				    this.$modal.msgSuccess("提取成功");
				    this.getList();
				});
			},
			/** 模板状态 */
			switchChange(item) {
				let text = item.status == 1 ? "停用" : "启用";
				var that = this
				uni.showModal({
					title: '系统提示',
					confirmColor: '#00a660',
					content: '确认 " ' + text + ' " 该模板吗？',
					success: function(res) {
						if (res.confirm) {
							let statusEx = item.status == 1 ? 0 : 1;
							const data = {
								id: item.id,
								status: statusEx
							}
							updateTemplateStatus(data).then(response => {
								that.getList()
								uni.showToast({
									title: text + '模板成功'
								});
							})
						} else if (res.cancel) {}
					}
				});
			},
			/** 确定修改合同类型 */
			dialogConfirm(){
			    this.$refs.form.validate().then((res) => {
			      if (this.form.id != null) {
			            updateContractType(this.form).then(response => {
			              this.$modal.msgSuccess("修改成功");
			              this.getList();
						  this.closed()
			            });
			          } else {
			            addContractType(this.form).then(response => {
			              this.$modal.msgSuccess("新增成功");
			              this.getList();
						  this.closed()
			            });
			          }
			      });	        
			},
			/** 模板设置  */
			setting(item){
				this.$tab.navigateTo('./templateSetting?id='+item.id)
			},
			/** 分享 */
			handleShare(item){
				uni.navigateTo({
					url:'./shareTemplate?id='+item.id+'&name='+item.name
				})
			},
			/** 编辑 */
			handleEdit(){
				this.$modal.msgError('请进入电脑端进行内容编辑！')
			},
			/** 删除 */
			handleDelete(item,index){
				let that = this 
				uni.showModal({
					title:'系统提示',
					content:'是否删除该模板？',
					confirmColor:'#00a660',
					success:function(res){
						if(res.confirm){
							delTemplate(item.id);
							that.templateList.splice(index,1)
							that.$modal.msgSuccess("删除成功");
						}else{
						}
					}
				})
			},
			/** 新建合同类型 */
			handleAdd(){
				this.$tab.navigateTo('./templateSetting')	
			},
		}
	}
</script>

<style scoped lang="scss">
	::v-deep .uni-navbar__header-btns-left {
	  width: 220rpx !important;
	}
	
	::v-deep .uni-navbar__header-btns-right {
	  width: 420rpx !important;
	}
	::v-deep .uni-navbar__header{
		height:50px !important;
	}
	::v-deep .card-actions-item{
		padding: 10rpx 40rpx;
	}
	.add_btn{
		background: $uni-color-primary;
		border: 1rpx solid #eee;
		color: #fff;
	}
	.add_btn:first-child{
		margin-right: 20rpx;
	}
	::v-deep .uni-forms-item__label{width: 150rpx !important;}
</style>
